package cn.lovelysia.ymcc.service.impl;

import cn.lovelysia.ymcc.domain.Login;
import cn.lovelysia.ymcc.domain.User;
import cn.lovelysia.ymcc.domain.UserAccount;
import cn.lovelysia.ymcc.domain.UserBaseInfo;
import cn.lovelysia.ymcc.dto.PhoneRegisterDto;
import cn.lovelysia.ymcc.exception.BusinessException;
import cn.lovelysia.ymcc.feignclient.IUaaFeignClient;
import cn.lovelysia.ymcc.mapper.UserAccountMapper;
import cn.lovelysia.ymcc.mapper.UserBaseInfoMapper;
import cn.lovelysia.ymcc.mapper.UserMapper;
import cn.lovelysia.ymcc.result.JSONResult;
import cn.lovelysia.ymcc.service.IUserService;
import cn.lovelysia.ymcc.util.AssertUtil;
import cn.lovelysia.ymcc.util.BitStatesUtils;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author elysia
 * @since 2022-12-04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Autowired
    private UserAccountMapper userAccountMapper;
    @Autowired
    private UserBaseInfoMapper userBaseInfoMapper;
    @Autowired
    private IUaaFeignClient uaaFeignClient;

    @Override
    public User findByPhone(String phone) {
        return userMapper.findByPhone(phone);
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void phoneRegister(PhoneRegisterDto phoneRegisterDto) {
        //1.对前端数据进行校验
        checkVerifyCode(phoneRegisterDto);
        //2.保存到t_login获取login_id
        //Login loginInfo = saveLogin(phoneRegisterDto);
        //Long loginId = loginInfo.getId();
        //AssertUtil.isNotEquals(loginId,-1L,"注册服务异常");
        Long loginId = saveLogin(phoneRegisterDto);

        //3.保存到用户表t_user
        User user = saveUser(phoneRegisterDto,loginId);
        //4.保存到t_user_account
        saveUserAccount(user);
        //5.保存到用户基本信息表t_user_base_info
        saveUserBaseInfo(user,phoneRegisterDto.getRegChannel());
    }

    private Long saveLogin(PhoneRegisterDto phoneRegisterDto) {
        Login login = new Login();
        login.setUsername(phoneRegisterDto.getMobile());
        login.setPassword(phoneRegisterDto.getPassword());
        login.setType(Login.LOG_WEB);
        JSONResult jsonResult =uaaFeignClient.phoneRegister(login);
        Long aLong = Long.valueOf(jsonResult.getData().toString());
        AssertUtil.isNotEquals(aLong,-1L,"注册服务异常");
        return aLong;
    }

    //3.
    private User saveUser(PhoneRegisterDto phoneRegisterDto, Long loginId) {
        User user = new User();
        user.setCreateTime(System.currentTimeMillis());
        user.setPhone(phoneRegisterDto.getMobile());
        user.setNickName(phoneRegisterDto.getMobile());
        //bitState
        long state = BitStatesUtils.addState(BitStatesUtils.OP_REGISTED, BitStatesUtils.OP_ACTIVED);
        //state = BitStatesUtils.addState(state,BitStatesUtils.OP_AUTHED_PHONE);
        user.setBitState(state);
        user.setSecLevel(0);
        user.setLoginId(loginId);
        userMapper.insert(user);
        return user;
    }

    //4.
    private void saveUserAccount(User user) {
        UserAccount userAccount = new UserAccount();
        userAccount.setId(user.getId());
        userAccount.setFrozenAmount(new BigDecimal("0"));
        userAccount.setUsableAmount(new BigDecimal("0"));
        userAccount.setCreateTime(System.currentTimeMillis());
        userAccountMapper.insert(userAccount);
    }

    //5.
    private void saveUserBaseInfo(User user, Integer regChannel) {
        UserBaseInfo userBaseInfo = new UserBaseInfo();
        userBaseInfo.setId(user.getId());
        userBaseInfo.setCreateTime(System.currentTimeMillis());
        userBaseInfo.setRegChannel(regChannel);
        userBaseInfo.setLevel(0);
        userBaseInfo.setGrowScore(0);
        userBaseInfoMapper.insert(userBaseInfo);
    }

    //封装校验数据的方法
    public void checkVerifyCode(PhoneRegisterDto phoneRegisterDto){
        //1.校验图形验证码是否过期
//        Object imageCodeObj = redisTemplate.opsForValue().get(phoneRegisterDto.getImageCode());
//        //AssertUtil.isNotNull(imageCodeObj,"图形验证码已过期");
//        if(imageCodeObj==null){
//            throw new BusinessException("图形验证码过期");
//        }
        //2.校验手机验证码是否正确
        Object phoneCodeObj = redisTemplate.opsForValue().get("register:" + phoneRegisterDto.getMobile());
        AssertUtil.isNotNull(phoneCodeObj,"短信验证码过期");
        String code = phoneCodeObj.toString().split(":")[0];
        AssertUtil.isEqualsIgnoreCase(phoneRegisterDto.getSmsCode(),code,"短信验证码错误");
    }

}
